<template>
  <div class="user-container">
    <!-- 数据展示  -->
    <DataList
      :arr="data!"
      :total="total"
      :page-num="pageNum"
      :page-size="pageSize"
      @page-hange="pageChange"
    >
      <template #title> 用户角色管理 </template>
      <template #headerLeft>
        <el-button :icon="Plus" type="primary" size="small" @click="addUserBtn">新增用户</el-button>
      </template>
      <template #default>
        <el-table-column prop="id" label="ID" width="60" />
        <el-table-column prop="nickname" label="用户昵称" width="120" />
        <el-table-column prop="avatar" label="头像" width="100">
          <template #default="scope">
            <el-avatar shape="square" fit="cover" :src="scope.row.avatar" />
          </template>
        </el-table-column>
        <el-table-column prop="phone" label="手机号" width="130" />
        <el-table-column prop="username" label="用户账号" width="130" />
        <el-table-column prop="email" label="邮箱" show-overflow-tooltip />
        <el-table-column prop="status" label="状态">
          <template #default="scope">
            <div style="display: flex; align-items: center">
              <el-tag v-if="scope.row.status === '01'" type="success">启用</el-tag>
              <el-tag v-else type="info">禁用</el-tag>
            </div>
          </template>
        </el-table-column>
        <el-table-column prop="lastLogin" label="上次登录时间" show-overflow-tooltip />
        <el-table-column prop="lastLoginIp" label="上一次登IP" show-overflow-tooltip />
        <el-table-column prop="lastUpdate" label="最后更新日期" show-overflow-tooltip />
        <el-table-column fixed="right" label="操作" width="200">
          <template #default="scope">
            <div style="display: flex; align-items: center">
              <el-button text bg size="small" type="primary" @click="userRoleBtn(scope.row.id)">
                用户角色
              </el-button>
              <el-button text bg size="small" type="warning" @click="editUserBtn(scope.row)">
                编辑
              </el-button>
            </div>
          </template>
        </el-table-column>
      </template>
    </DataList>
    <!-- 新增用户抽屉 -->
    <el-drawer title="新增用户" v-model="addUserDrawer" @closed="addUserCancel">
      <el-form
        ref="addUserFormRef"
        :model="addUserForm"
        :rules="addUserFormRule"
        label-width="80px"
      >
        <el-form-item label="用户账号" prop="username">
          <el-input placeholder="用户账号" v-model.trim="addUserForm.username"></el-input>
        </el-form-item>
        <el-form-item label="手机号" prop="phone">
          <el-input placeholder="手机号" v-model.trim="addUserForm.phone"></el-input>
        </el-form-item>
        <el-form-item label="是否启用" prop="status">
          <el-switch
            v-model.trim="addUserForm.status"
            active-value="01"
            inactive-value="00"
          ></el-switch>
        </el-form-item>
        <el-form-item>
          <el-button @click="addUserCancel" plain>取消</el-button>
          <el-button type="primary" @click="addUserSubmit">提交</el-button>
        </el-form-item>
      </el-form>
    </el-drawer>
    <!-- 编辑用户抽屉 -->
    <el-drawer title="编辑用户" v-model="editUserDrawer" @closed="editUserCancel">
      <el-form ref="editUserFormRef" :model="editForm" :rules="editUserRole" label-width="auto">
        <el-form-item label="手机号" prop="phone">
          <el-input placeholder="填写手机号" v-model="editForm.phone"></el-input>
        </el-form-item>
        <el-form-item label="是否启用" prop="status">
          <el-switch v-model="editForm.status" active-value="01" inactive-value="00"></el-switch>
        </el-form-item>
        <el-form-item>
          <el-button @click="editUserCancel">取消</el-button>
          <el-button type="primary" @click="editUserSubmit">提交</el-button>
        </el-form-item>
      </el-form>
    </el-drawer>
    <!-- 角色绑定抽屉 -->
    <el-drawer title="用户角色关联" v-model="userRoleDrawer">
      <el-button type="primary" @click="saveUserRole" style="margin-bottom: 15px">保存</el-button>
      <el-tree-v2
        ref="userRoleRef"
        show-checkbox
        :data="roles"
        :props="{ value: 'id', label: 'roleName' }"
      />
    </el-drawer>
  </div>
</template>

<script lang="ts" setup>
import DataList from '@/components/DataList.vue'
import { Plus } from '@element-plus/icons-vue'
import { ElTreeV2 as Tree2 } from 'element-plus'
import {
  getUserList,
  addUser,
  updateUser,
  getRelation,
  getRoleConcise,
  updateRelation
} from '@/api/system/user'
const PHONE_REGEX =
  /^((13[0-9])|(14[0|5|6|7|9])|(15[0|1|2|3|5|6|7|8|9])|(16[2|5|6|7])|(17[0|1|2|3|5|6|7|8])|(18[0-9])|(19[0|1|2|3|5|6|7|8|9]))\d{8}$/

/**
 * 分页参数
 */
const pageNum = ref(1)
const pageSize = ref(10)
const total = ref(0)
const data = ref<User[]>([])

function toGetList() {
  getUserList({ pageNum: pageNum.value, pageSize: pageSize.value }).then((res) => {
    if (res.code === 200) {
      data.value = res.data?.list!
      total.value = res.data?.total!
    }
  })
}

// 分页改变
function pageChange(num: number, size: number) {
  pageNum.value = num
  pageSize.value = size
  toGetList()
}
/**
 * 用户新增
 */
const addUserDrawer = ref(false)
const addUserFormRef = ref<FormInstance>()
const addUserForm = ref<User>({
  username: '',
  status: '01',
  phone: ''
})
const addUserFormRule = reactive<FormRules<User>>({
  username: [
    { required: true, message: '请输入用户名' },
    { pattern: /^(?!\d+$).+/, message: '用户名不能为纯数字' }
  ],
  status: { required: true },
  phone: [
    { required: true, message: '请输入手机号' },
    { pattern: PHONE_REGEX, message: '请输入正确的手机号' }
  ]
})

// 新增用户按钮
function addUserBtn() {
  addUserDrawer.value = true
}
// 新增用户取消
function addUserCancel() {
  addUserDrawer.value = false
  addUserForm.value.username = ''
  addUserForm.value.status = '01'
  addUserForm.value.phone = ''
}
// 新增用户提交
function addUserSubmit() {
  addUser(addUserForm.value).then((res) => {
    if (res.code === 200) {
      ElMessage({
        message: '保存成功',
        type: 'success'
      })
      addUserCancel()
      toGetList()
    }
  })
}
/**
 * 更新用户
 */
const editUserDrawer = ref(false)
const editUserFormRef = ref()
const editUserRole = reactive({
  status: { required: true },
  phone: [
    { required: true, message: '请输入手机号' },
    { pattern: PHONE_REGEX, message: '请输入正确的手机号' }
  ]
})
const editForm = ref<User>({
  id: 0,
  status: '01',
  phone: ''
})
// 编辑角色按钮
function editUserBtn(user: User) {
  editForm.value.id = user.id
  editForm.value.status = user.status
  editForm.value.phone = user.phone
  editUserDrawer.value = true
}
// 取消编辑
function editUserCancel() {
  editUserDrawer.value = false
  editForm.value.id = 0
  editForm.value.status = '01'
  editForm.value.phone = ''
}
// 编辑提交
function editUserSubmit() {
  updateUser(editForm.value).then((res) => {
    if (res.code === 200) {
      ElMessage({
        message: '保存成功',
        type: 'success'
      })
      editUserCancel()
      toGetList()
    }
  })
}
/**
 * 用户角色
 */
const userRoleRef = ref<InstanceType<typeof Tree2>>()
const userRoleDrawer = ref(false)
const roles = ref<Role[]>()
const userId = ref(0)
// 用户角色点击
function userRoleBtn(id: number) {
  userRoleDrawer.value = true
  userId.value = id
  getRelation(id).then((res) => {
    if (res.code === 200) {
      let relation = res.data!
      userRoleRef.value?.setCheckedKeys(relation)
    }
  })
}
// 保存用户角色关联
function saveUserRole() {
  let roleIds = userRoleRef.value?.getCheckedKeys(false) as number[]
  updateRelation(userId.value, roleIds).then((res) => {
    if (res.code === 200) {
      ElMessage({
        message: '保存成功',
        type: 'success'
      })
      userRoleDrawer.value = false
    }
  })
}

// 生命钩子
onMounted(() => {
  toGetList()
  getRoleConcise().then((res) => {
    if (res.code === 200) {
      roles.value = res.data
    }
  })
})
</script>

<style lang="scss" scoped>
.user-container {
  width: 100%;
  height: 100%;
  .title {
    margin-bottom: 13px;
    span {
      font-size: 16px;
      font-weight: 500;
    }
  }
  .el-card {
    height: calc(100% - 77px);
  }
  :deep(.el-card__footer) {
    border: none;
  }
  .footer-content {
    display: flex;
    align-items: center;
    justify-content: end;
  }
}
</style>
